from django.db import models
from django.contrib.auth.models import AbstractUser
from system.models import CommonInfo
from crum import get_current_user

# Create your models here.
class User(AbstractUser):
    GENDER_CHOICES = (
        ('male', '男'),
        ('female', '女'),
        ('secret', '保密'),
    )
    nickname = models.CharField(verbose_name='昵称', max_length=20, null=True, blank=True, db_comment='昵称')
    gender = models.CharField(verbose_name='性别', max_length=10, null=False, blank=False, choices=GENDER_CHOICES, default='secret', db_comment='性别')
    birthday = models.DateField(verbose_name='生日', null=True, blank=True, db_comment='生日')
    id_card = models.CharField(verbose_name='身份证号码', max_length=18, null=True, blank=True, db_comment='身份证号码')
    mobile_num = models.CharField(verbose_name='手机号码', max_length=11, null=True, blank=True, db_comment='手机号码')
    avatar = models.ImageField(verbose_name='头像', upload_to='avatar/%Y/%m/%d', null=True, blank=True, db_comment='头像')
    signature = models.CharField(verbose_name='签名', max_length=200, null=True, blank=True, db_comment='签名')
    roles = models.ManyToManyField('Role', through='UserRole', verbose_name='角色', related_name='users')

    class Meta:
        db_table = 'user'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

# 角色
class Role(CommonInfo):
    name = models.CharField(verbose_name='角色名称', max_length=100, null=False, blank=False, db_comment='角色名称')
    description = models.CharField(verbose_name='描述', max_length=200, null=True, blank=True, db_comment='描述')
    remark = models.CharField(verbose_name='备注', max_length=200, null=True, blank=True, db_comment='备注')
    sort_num = models.IntegerField(verbose_name='排序号', null=True, blank=True, db_comment='排序号')
    menus = models.ManyToManyField('system.Menu', through='system.RoleMenu', verbose_name='菜单', related_name='roles')

    def __str__(self):
        return self.name
    
    class Meta:
        db_table = 'role'
        verbose_name = '角色'
        verbose_name_plural = verbose_name

# 用户角色关联
class UserRole(CommonInfo):
    user = models.ForeignKey(User, related_name='user_roles', on_delete=models.CASCADE, verbose_name='用户', db_column='user_id', db_comment='用户ID')
    role = models.ForeignKey(Role, related_name='role_users', on_delete=models.CASCADE, verbose_name='角色', db_column='role_id', db_comment='角色ID')
    whether_main = models.IntegerField(verbose_name='是否主角色', choices=((0, '否'), (1, '是')), default=1, db_comment='是否主角色')
    class Meta:
        db_table = 'user_role'
        verbose_name = '用户角色'
        verbose_name_plural = verbose_name
        constraints = [
            # 联合唯一索引，保证用户和角色的唯一性
            models.UniqueConstraint(fields=['user', 'role'], name='unique_user_role'),
            # 权限约束，一个用户只能对应一个主角色
            models.UniqueConstraint(fields=['user', 'whether_main'], name='unique_user_main_role')
        ]
    def __str__(self):
        return self.user.nickname + '-' + self.role.name
    
    # 保存时自动更新创建人和更新人
    def save(self, *args, **kwargs):
        user = get_current_user()
        if user and not user.is_anonymous:
            if not self.pk: # 新增
                self.create_user = user.id
            self.update_user = user.id
        super().save(*args, **kwargs)